package com.tiger.poker.controller;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.tiger.poker.entity.Player;
import com.tiger.poker.enums.PlayerOperationStatusEnum;
import com.tiger.poker.util.GameUtil;
import com.tiger.poker.util.WebSocketUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Optional;
import java.util.Set;

import static com.tiger.poker.util.GameUtil.*;


/**
 * The type Web socket.
 *
 * @author joy
 */
@Component
@ServerEndpoint("/GoldenFlowers")
@Slf4j
public class GoldenFlowers {

    private static final int MAX_PLAYER = 5;
    public static final String MESSAGE_SEPARATOR = "2sep1";

    private Session session;

    public static final Set<Player> PLAYER_SET = Collections.synchronizedSet(new LinkedHashSet<>());

    public static int score = 0;

    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        if (PLAYER_SET.size() >= MAX_PLAYER) {
            WebSocketUtil.sendMessage(this.session, "游戏人满了,请稍后");
        }

    }

    @OnClose
    public void onClose() throws JsonProcessingException {

        Optional<Player> optionalVo = PLAYER_SET.stream().filter(player -> player.getSession().equals(this.session)).findAny();
        if (optionalVo.isPresent()) {
            Player player = optionalVo.get();
            if (player.getOperationStatus() == PlayerOperationStatusEnum.ENABLE.getCode()){
                changeOperationStatus(PLAYER_SET, player);
            }
            log.info("{},  离开了游戏", player.getName());
            PLAYER_SET.remove(player);
            WebSocketUtil.sendMessageBatch(PLAYER_SET, SHOW_MESSAGE + MESSAGE_SEPARATOR + player.getName() + " 离开了游戏");
            WebSocketUtil.sendMessageBatch(GoldenFlowers.PLAYER_SET,GameUtil.assemble(UPDATE_DATA,
                    MAPPER.writeValueAsString(GoldenFlowers.PLAYER_SET)));
        }
    }

    @OnMessage
    public void onMessage(String message) {
        log.info("收到客户端发来的消息：{}", message);

        String[] typeAndContents = message.split(MESSAGE_SEPARATOR);
        String type = typeAndContents[0];
        String content = typeAndContents[1];

        try {
            GameUtil.resolveMessage(Integer.parseInt(type), content, session);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
